package com.example.homeworkmanagement.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.example.homeworkmanagement.dto.ClassesAndStudentsDTO;
import com.example.homeworkmanagement.pojo.Notifications;
import com.example.homeworkmanagement.pojo.Students;
import com.example.homeworkmanagement.mapper.StudentsMapper;
import com.example.homeworkmanagement.service.StudentsService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.example.homeworkmanagement.vo.ResultVO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author 拒绝加班
 * @since 2025-05-25
 */
@Service
public class StudentsServiceImpl extends ServiceImpl<StudentsMapper, Students> implements StudentsService {
    @Autowired
    private StudentsMapper studentsMapper;

    @Override
    public ResultVO<Students> login(String student_id, String password) throws Exception {
        QueryWrapper<Students> qw = new QueryWrapper<>();
        qw.eq("student_id", student_id);
        // 获取一个
        Students students = this.getOne(qw);

        if (students != null) {
            if (students.getPassword().equals(password)) {
                // 返回用户信息和角色信息
                return ResultVO.success("登录成功", students);
            } else {
                return ResultVO.fail("密码错误");
            }
        }
        return ResultVO.fail("账号不存在");
    }

    @Override
    public ResultVO<List<Students>> getStudentList(Students student, int page, int size) {
        try {
            QueryWrapper<Students> queryWrapper = new QueryWrapper<>();

            // 学生学号（模糊查询，自动去空格）
            String studentId = student.getStudentId();
            if (studentId != null && !studentId.trim().isEmpty()) {
                queryWrapper.like("student_id", studentId.trim());
            }

            // 学生姓名（模糊查询）
            String studentName = student.getStudentName();
            if (studentName != null && !studentName.trim().isEmpty()) {
                queryWrapper.like("student_name", studentName.trim());
            }

            // 班级ID（精确查询，字符串类型需处理空串）
            String classId = student.getClassId(); // 确认实体类中为String类型
            if (classId != null && !classId.trim().isEmpty()) {
                queryWrapper.eq("class_id", classId.trim()); // 添加trim()避免空格影响
            }

            // 性别（精确查询）
            String gender = student.getGender();
            if (gender != null && !gender.trim().isEmpty()) {
                queryWrapper.eq("gender", gender.trim());
            }

            // 联系电话（模糊查询）
            String phone = student.getPhone();
            if (phone != null && !phone.trim().isEmpty()) {
                queryWrapper.like("phone", phone.trim());
            }

            // 年龄（精确查询）
            Integer age = student.getAge();
            if (age != null) {
                queryWrapper.eq("age", age);
            }

            // 邮箱（模糊查询）
            String email = student.getEmail();
            if (email != null && !email.trim().isEmpty()) {
                queryWrapper.like("email", email.trim());
            }

            // 分页查询（泛型修正为Students）
            Page<Students> pageResult = this.page(new Page<>(page, size), queryWrapper);

            List<Students> list = this.list(queryWrapper);
            int total= list.size();

            // 返回当前页数据列表
            return ResultVO.success("学生列表获取成功", pageResult.getRecords(),total);
        } catch (Exception e) {
            return ResultVO.fail("获取学生列表时发生异常：" + e.getMessage());
        }
    }
    @Override
    public ResultVO<Students> getStudentDetail(String studentId) {
        try {
            Students student = this.getOne(new QueryWrapper<Students>().eq("student_id", studentId));
            if (student == null) {
                return ResultVO.fail("学生学号不存在");
            }
            return ResultVO.success("学生详情获取成功", student);
        } catch (Exception e) {
            return ResultVO.fail("获取学生详情时发生异常：" + e.getMessage());
        }
    }

    @Override
    public ResultVO<Students> addStudent(Students student) {
        try {
            // 检查学号是否已存在
            Students existingStudent = this.getOne(new QueryWrapper<Students>().eq("student_id", student.getStudentId()));
            if (existingStudent != null) {
                return ResultVO.fail("该学号已存在");
            }

            boolean saveSuccess = this.save(student);
            if (!saveSuccess) {
                return ResultVO.fail("学生添加失败");
            }
            return ResultVO.success("学生添加成功", student);
        } catch (Exception e) {
            return ResultVO.fail("添加学生时发生异常：" + e.getMessage());
        }
    }

    @Override
    public ResultVO<Students> updateStudent(Students student) {
        try {
            // 检查学生是否存在
            Students existingStudent = this.getOne(new QueryWrapper<Students>().eq("student_id", student.getStudentId()));
            if (existingStudent == null) {
                return ResultVO.fail("学生学号不存在");
            }

            // 更新字段（只更新非空值）
            if (student.getStudentName() != null && !student.getStudentName().isEmpty()) existingStudent.setStudentName(student.getStudentName());
            if (student.getPassword() != null && !student.getPassword().isEmpty()) existingStudent.setPassword(student.getPassword());
            if (student.getClassId() != null && !student.getClassId().isEmpty()) existingStudent.setClassId(student.getClassId());
            if (student.getGender() != null && !student.getGender().isEmpty()) existingStudent.setGender(student.getGender());
            if (student.getPhone() != null && !student.getPhone().isEmpty()) existingStudent.setPhone(student.getPhone());
            if (student.getEmail() != null && !student.getEmail().isEmpty()) existingStudent.setEmail(student.getEmail());
            if (student.getAge() != null) existingStudent.setAge(student.getAge());

            boolean updateSuccess = this.updateById(existingStudent);
            if (!updateSuccess) {
                return ResultVO.fail("学生信息更新失败");
            }
            return ResultVO.success("学生信息更新成功", existingStudent);
        } catch (Exception e) {
            return ResultVO.fail("更新学生时发生异常：" + e.getMessage());
        }
    }

    @Override
    public ResultVO<String> deleteStudent(String studentId) {
        try {
            // 检查学生是否存在
            Students existingStudent = this.getOne(new QueryWrapper<Students>().eq("student_id", studentId));
            if (existingStudent == null) {
                return ResultVO.fail("学生学号不存在");
            }

//            //检查学生是否在提交作业里，已有记录的不可以删除
//            QueryWrapper<Submissions> queryWrapper = new QueryWrapper<>();
//            queryWrapper.eq("student_id",studentId);
//            List<Submissions> submissionsList=submissionsMapper.selectList(queryWrapper);
//            if(!submissionsList.isEmpty()){
//                return ResultVO.fail("该学生在提交作业里已有记录，不可以删除");
//            }

            boolean deleteSuccess = this.removeById(studentId);
            if (!deleteSuccess) {
                return ResultVO.fail("学生删除失败");
            }
            return ResultVO.success("学生删除成功", "");
        } catch (Exception e) {
            return ResultVO.fail("删除学生时发生异常：" + e.getMessage());
        }
    }

    @Override
    public ResultVO<Integer> selectStudentCountByClassId(String classId) {
        int count = studentsMapper.selectStudentCountByClassId(classId);
        if(count==0){
            return ResultVO.fail("该班级下没有学生");
        }
        return ResultVO.success("查询成功",count);

    }

    @Override
    public ResultVO<List<Students>> selectStudentListByClassIds(String classIds, int page, int size) {
        try {
            // 参数校验
            if (classIds==null || classIds=="") {
                return ResultVO.fail("班级ID列表不能为空");
            }
            // 创建查询条件
            QueryWrapper<Students> queryWrapper = new QueryWrapper<>();

            // 处理班级ID列表（将逗号分隔的字符串转为列表条件）
            String[] classIdArray = classIds.split(",");
            List<String> classIdList = new ArrayList<>();

            for (String id : classIdArray) {
                if (id != null && !id.trim().isEmpty()) {
                    classIdList.add(id.trim());
                }
            }

            // 如果处理后的班级ID列表不为空，则添加IN条件
            if (!classIdList.isEmpty()) {
                queryWrapper.in("class_id", classIdList);
            } else {
                // 如果所有ID都是空字符串，直接返回空结果
                return ResultVO.fail("班级ID列表不能为空");
            }

            // 分页查询
            Page<Students> pageResult = this.page(new Page<>(page, size), queryWrapper);

            List<Students> list = this.list(queryWrapper);
            int total= list.size();

            // 返回当前页数据列表
            return ResultVO.success("学生列表获取成功", pageResult.getRecords(),total);
        } catch (Exception e) {
            log.error("查询学生列表失败", e);
            return ResultVO.fail("获取学生列表时发生异常：" + e.getMessage());
        }
    }

    @Override
    public ResultVO<ClassesAndStudentsDTO> selectStudentAndClassInfo(String studentId) {
        try {
            ClassesAndStudentsDTO classesAndStudentsDTO = studentsMapper.selectStudentAndClassInfo(studentId);
            if (classesAndStudentsDTO == null) {
                return ResultVO.fail("未找到该学生");
            }
            return ResultVO.success("查询成功", classesAndStudentsDTO);
        } catch (Exception e) {
            return ResultVO.fail("查询学生及班级信息时发生异常：" + e.getMessage());
        }
    }
}
